package zuel.innovation.disley.project.controller;

import cn.fabrice.common.constant.BaseConstants;
import cn.fabrice.common.pojo.DataResult;
import cn.fabrice.jfinal.annotation.Param;
import cn.fabrice.jfinal.annotation.ValidateParam;
import cn.fabrice.jfinal.constant.ValidateRuleConstants;
import cn.fabrice.jfinal.ext.cros.interceptor.CrossInterceptor;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import zuel.innovation.disley.common.module.Project;
import zuel.innovation.disley.common.module.ProjectGroup;
import zuel.innovation.disley.common.module.User;
//import zuel.innovation.disley.project.service.GroupofprojectService;
//import zuel.innovation.disley.project.service.ProjectService;

import zuel.innovation.disley.project.service.ProjectGroupService;
import zuel.innovation.disley.project.service.ProjectService;
import zuel.innovation.disley.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Before(CrossInterceptor.class)
@Path("/project")
@ValidateParam
public class ProjectController extends Controller {
    @Inject
    ProjectService projectService;
    @Inject
    UserService userService;
    @Inject
    ProjectGroupService ProjectGroupService;


    /**
     * 管理员查看项目信息(分页展示)
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllProjectsByPages(int page, int pageSize) {
        Page<Record> projects = Db.paginate(page, pageSize, "select p_id,p_race,p_name,u_name,p_state,p_start,p_end ", "from project INNER JOIN `user` on p_leader = u_id");
        renderJson(DataResult.data(projects));
    }

    /**
     * 管理员查看已结束的项目数目
     */
    public void countFinishedProjects() {
        Project FinishedProjects = projectService.get("countFinishedProjects");
        renderJson(DataResult.data(FinishedProjects));
    }

    /**
     * 管理员查看已结束的项目详情
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getFinishedProjectsByPages(int page, int pageSize) {
        Page<Record> projects = Db.paginate(page, pageSize, "select *", "from project where p_deleted=0 and p_state=1");
        renderJson(DataResult.data(projects));
    }


    /**
     * 管理员查看进行中的项目数目
     */
    public void countOngoingProjects() {
        Project OngoingProjects = projectService.get("countOngoingProjects");
        renderJson(DataResult.data(OngoingProjects));
    }

    /**
     * 管理员查看进行中的项目详情
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getOngoingProjectsByPages(int page, int pageSize) {
        Page<Record> projects = Db.paginate(page, pageSize, "select *", "from project where p_deleted=0 and p_state=0");
        renderJson(DataResult.data(projects));
    }

    /**
     * 显示项目工期
     *
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void showProjectTime(int pId) {
        Kv cond = Kv.by("pId", pId);
        Project project = projectService.get(cond, "showProjectTime");
        renderJson(DataResult.data(project));
    }

    /**
     * 显示项目剩余工期
     *
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void showProjectRemainTime(int pId) {
        Kv cond = Kv.by("pId", pId);
        Project project = projectService.get(cond, "showProjectRemainTime");
        renderJson(DataResult.data(project));
    }

    /**
     * 查看项目具体信息
     *
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void getProjectsDetails(int pId) {
        Kv cond = Kv.by("pId", pId);
        Project project = projectService.get(cond, "getProjectsDetails");
        renderJson(DataResult.data(project));
    }

    /**
     * 新建项目
     *
     * @param pRace         比赛名称
     * @param pName         项目名称
     * @param pPhone        负责人手机
     * @param pEmail        负责人邮箱
     * @param pType         项目类别 0-其他 1-开发 2-算法
     * @param pStart        开始时间
     * @param pEnd          截止时间
     * @param pIntroduction 项目介绍
     * @param gMember       项目小组成员
     */
    @Param(name = "pRace", required = false)
    @Param(name = "pName", required = true)
    @Param(name = "pPhone", required = true, rule = ValidateRuleConstants.Key.MOBILE)
    @Param(name = "pEmail", required = true, rule = ValidateRuleConstants.Key.EMAIL)
    @Param(name = "pType", required = true)
    @Param(name = "pStart", required = true, rule = ValidateRuleConstants.Key.DATE)
    @Param(name = "pEnd", required = true, rule = ValidateRuleConstants.Key.DATE)
    @Param(name = "pIntroduction", required = true)
    @Param(name = "gMember", required = false)
    public void addNewProject(String pRace, String pName, String pPhone, String pEmail, int pType, Date pStart, Date pEnd, String gMember, String pIntroduction) throws ParseException {
        Project project = new Project();
        //新建一个json格式的对象，用来存储新增项目的信息
        JSONObject newProject = new JSONObject();
        project.setPRace(pRace);
        project.setPName(pName);
        project.setPPhone(pPhone);
        project.setPEmail(pEmail);
        project.setPType(pType);
        project.setPIntroduction(pIntroduction);
        project.setPStart(pStart);
        project.setPEnd(pEnd);
        SimpleDateFormat pdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date pCreate = pdf.parse(pdf.format(System.currentTimeMillis()));
        project.setPCreate(pCreate);
        // 根据token获取负责人Id
        int leaderId = getAttr(BaseConstants.ACCOUNT_ID);
        project.setPLeader(leaderId);
        //根据负责人Id获取负责人姓名
        Kv lId = Kv.by("lId", leaderId);
        User leader = userService.get(lId, "getByLeaderId");
        String leaderName = leader.getUName();
        //添加项目信息
        newProject.put("pRace", pRace);
        newProject.put("pName", pName);
        newProject.put("pPhone", pPhone);
        newProject.put("pEmail", pEmail);
        newProject.put("pType", pType);
        newProject.put("pIntroduction", pIntroduction);
        newProject.put("pStart", pStart);
        newProject.put("pEnd", pEnd);
        newProject.put("leaderName", leaderName);
        //事务处理
        boolean flag = Db.tx(() -> {
            if (!project.save()){
                return false;
            }
            ProjectGroup g = new ProjectGroup();
            g.setGLeader(leaderId);
            g.setGId(project.getPId());
            g.setGMember(leaderId);
            SimpleDateFormat d = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                Date g_create = d.parse(d.format(System.currentTimeMillis()));
                g.setGCreate(g_create);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            g.save();
            //小组成员只有创建者自己
            if (gMember != null) {
                // 获取组员编号
                String[] arrays = gMember.split(",");
                for (int i = 0; i < arrays.length; i++) {
                    ProjectGroup group = new ProjectGroup();
                    group.setGLeader(leaderId);
                    group.setGMember(Integer.parseInt(arrays[i]));
                    //根据组员Id获取组员姓名
                    Kv cond = Kv.by("uId", arrays[i]);
                    User user = userService.get(cond, "getUserById");
                    String name = user.getUName();
                    newProject.put("gMember" + Integer.toString(i), name);
                    //获取当前时间
                    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    try {
                        Date g_create = df.parse(df.format(System.currentTimeMillis()));
                        group.setGCreate(g_create);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    group.setGId(project.getPId());
                    group.save();
                }
            }
            return true;
        });
        renderJson(flag?DataResult.data(newProject): DataResult.error403());
    }

    /**
     * 结束项目
     *
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void endProject(int pId) {
        Kv cond = Kv.by("pId", pId);
        Project project = projectService.get(cond, "getProject");
        project.setPState(1);
        project.setPId(pId);
        renderJson(project.update() ? DataResult.data(project) : DataResult.fail());
    }


    /**
     * 用户查看自己参与的项目
     */
    public void showProjectsOfMine() {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("gMember", id);
        List<Project> projects = projectService.list(cond, "showProjectsOfMine");
        renderJson(DataResult.data(projects));

    }

    /**
     * 用户查看自己参与的进行中项目数量
     */
    public void showOngoingProjectsNumOfMine() {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("gMember", id);
        Project pNum = projectService.get(cond, "showOngoingProjectsNumOfMine");
        renderJson(DataResult.data(pNum));
    }

    /**
     * 用户查看自己参与的已结束项目数量
     */
    public void showFinishedProjectsNumOfMine() {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("gMember", id);
        Project pNum = projectService.get(cond, "showFinishedProjectsNumOfMine");
        renderJson(DataResult.data(pNum));

    }

    /**
     * 用户查看自己负责的项目
     */
    public void showProjectsOfMyLeading() {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("gLeader", id);
        List<Project> projects = projectService.list(cond, "getLeadingProjectsByGLeader");
        renderJson(DataResult.data(projects));







    }



    /**
     * 项目负责人修改项目信息
     *
     * @param pId    项目编号
     * @param pName  项目名称
     * @param pPhone 负责人手机
     * @param pEmail 负责人邮箱
     * @param pType  项目类别 0-其他 1-开发 2-算法
     * @param pState 项目状态 0-进行中 1-已结束
     * @param pStart 开始时间
     * @param pEnd   截止时间
     * @param pMoney 项目奖金
     * @param pAward 项目奖项
     */
    @Param(name = "pRace", required = false)
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    @Param(name = "pName", required = true)
    @Param(name = "pPhone", required = true, rule = ValidateRuleConstants.Key.MOBILE)
    @Param(name = "pEmail", required = true, rule = ValidateRuleConstants.Key.EMAIL)
    @Param(name = "pType", required = true)
    @Param(name = "pState", required = true)
    @Param(name = "pStart", required = true, rule = ValidateRuleConstants.Key.DATE)
    @Param(name = "pEnd", required = true, rule = ValidateRuleConstants.Key.DATE)
    public void updateProjectByLeader(int pId, String pRace, String pName, String pPhone, String pEmail, int pType, int pState, Date pStart, Date pEnd, String pMoney, String pAward) throws ParseException {
        Kv cond = Kv.by("pId", pId);
        Project project = projectService.get(cond, "getProjectsDetails");
        project.setPName(pName);
        project.setPRace(pRace);
        project.setPPhone(pPhone);
        project.setPEmail(pEmail);
        project.setPType(pType);
        project.setPState(pState);
        project.setPStart(pStart);
        project.setPEnd(pEnd);
        project.setPMoney(pMoney);
        project.setPAward(pAward);
        //获取当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date p_update = df.parse(df.format(System.currentTimeMillis()));
        project.setPUpdate(p_update);
        renderJson(project.update() ? DataResult.data(project) : DataResult.fail());
    }


    /**
     * 修改项目简介
     *
     * @param pId           项目编号
     * @param pIntroduction 项目介绍
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    @Param(name = "pIntroduction", required = true)
    public void updatePIntroduction(int pId, String pIntroduction) throws ParseException {
        Kv cond = Kv.by("pId", pId);
        Project project = projectService.get(cond, "getPIntroduction");
        project.setPId(pId);
        project.setPIntroduction(pIntroduction);
        //获取当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date p_update = df.parse(df.format(System.currentTimeMillis()));
        project.setPUpdate(p_update);
        renderJson(project.update() ? DataResult.data(project) : DataResult.fail());
    }

    /**
     * 查看项目小组成员信息
     *
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void getProjectMember(int pId) {
        Kv cond = Kv.by("pId", pId);
        List<ProjectGroup> groupList = ProjectGroupService.list(cond, "showGroupDetails");
        renderJson(DataResult.data(groupList));
    }

    /**
     * 查看项目小组成员数量
     *
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void getProjectMemberNum(int pId) {
        Kv cond = Kv.by("pId", pId);
        ProjectGroup num = ProjectGroupService.get(cond, "getProjectMemberNum");
        renderJson(DataResult.data(num));
    }

    /**
     * 删除项目成员
     *
     * @param pId     项目编号
     * @param gMember 项目小组成员
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    @Param(name = "gMember", required = true)
    public void deleteProjectMember(int pId, int gMember) {
        Kv cond = Kv.by("pId", pId).set("gMember", gMember);
        ProjectGroup group = ProjectGroupService.get(cond, "deleteProjectMember");
        group.setGDeleted(1);
        renderJson(group.update() ? DataResult.data(group) : DataResult.fail());
    }


    /**
     * 添加项目成员
     *
     * @param pId     项目编号
     * @param gMember 项目小组成员
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    @Param(name = "gMember", required = true)
    public void addProjectMember(int pId, String gMember) throws ParseException {
        Kv cond = Kv.by("pId", pId);
        ProjectGroup g = ProjectGroupService.get(cond, "showGroupDetails");
        int g_leader = g.getGLeader();
        String[] arrays = gMember.split(",");
        for (int i = 0; i < arrays.length; i++) {
            ProjectGroup group = new ProjectGroup();
            group.setGId(pId);
            group.setGLeader(g_leader);
            group.setGMember(Integer.parseInt(arrays[i]));
            //获取当前时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date g_create = df.parse(df.format(System.currentTimeMillis()));
            group.setGCreate(g_create);
            group.save();
            renderJson(DataResult.data(group));
        }
    }

    /**
     * 获得不在该项目成员名单里的团队成员
     * @param pId 项目编号
     */
    @Param(name = "pId", required = true, rule = ValidateRuleConstants.Key.ID)
    public void getDisIncludedProjectMember(int pId){
        Kv cond = Kv.by("pId",pId);
        List<User> userList = userService.list(cond,"getDisIncludedProjectMember");
        renderJson(DataResult.data(userList));
    }

    /**
     * 根据比赛名称进行搜索
     *
     * @param pRace 比赛名称
     */
    @Param(name = "pRace", required = true)
    public void searchByRaceName(String pRace) {
        Kv cond = Kv.by("pRace", pRace);
        List<Project> projectList = projectService.list(cond, "searchByRaceName");
        renderJson(DataResult.data(projectList));
    }

    /**
     * 根据项目名称进行搜索
     *
     * @param pName 项目名称
     */
    @Param(name = "pName", required = true)
    public void searchByProjectName(String pName) {
        Kv cond = Kv.by("pName", pName);
        List<Project> projectList = projectService.list(cond, "searchByProjectName");
        renderJson(DataResult.data(projectList));
    }

    /**
     * 根据负责人姓名进行搜索
     *
     * @param pLeader 负责人姓名
     */
    @Param(name = "pLeader", required = true)
    public void searchByLeaderName(String pLeader) {
        Kv cond = Kv.by("pLeader", pLeader);
        List<Project> projectList = projectService.list(cond, "searchByLeaderName");
        renderJson(DataResult.data(projectList));
    }
}
